package com.alibaba.citrus.cr.platform.enhance.facade.service.scitem;

import com.alibaba.citrus.cr.common.annotation.FacadeInvoker;
import com.alibaba.citrus.cr.common.exception.FacadeException;
import com.alibaba.citrus.cr.common.util.PageUtils;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.model.dto.BaselineGetOrganizationByCodes2Request;
import com.epoch.app.bcorder.model.dto.BaselineGetOrganizationByCodes2Response;
import com.epoch.app.bcorder.model.dto.BaselineGetOrganizationByIds2Request;
import com.epoch.app.bcorder.model.dto.BaselineGetOrganizationByIds2Response;
import com.epoch.app.bcorder.model.dto.BaselineQueryScItemByPageFromDbRequest;
import com.epoch.app.bcorder.model.dto.EmployeeGetCurrentLoginResponse;
import com.epoch.app.bcorder.model.dto.GetLoginEmployeeInfoResponse;
import com.epoch.app.bcorder.model.dto.OrganizationSDO;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.bcorder.service.BcOrderService;
import com.epoch.app.crplatformenhance.enums.OrganizationTypeEnum;
import com.epoch.app.crplatformenhance.model.dto.GetDownOrganizationListRequest;
import com.epoch.app.crplatformenhance.model.dto.GetTopOrganizationListRequest;
import com.epoch.app.crplatformenhance.model.dto.ScItemDBresponse;
import com.epoch.app.crplatformenhance.model.dto.ScItemManageRangeBatchDeleteRequest;
import com.epoch.app.crplatformenhance.model.dto.ScItemManageRangeCreateRequest;
import com.epoch.app.crplatformenhance.model.dto.ScItemManageRangeImportListRequest;
import com.epoch.app.crplatformenhance.model.dto.ScItemManageRangeImportRequest;
import com.epoch.app.crplatformenhance.model.dto.ScItemManageRangeLoadListRequest;
import com.epoch.app.crplatformenhance.model.dto.ScItemResult;
import com.epoch.app.crplatformenhance.model.dto.ScItemSDO;
import com.epoch.app.crplatformenhance.model.dto.ScItemSearchResult;
import com.epoch.app.crplatformenhance.model.dto.TopOrganizationListResponse;
import com.epoch.app.crplatformenhance.model.enums.ScItemManageRangeStatus;
import com.epoch.app.crplatformenhance.scitemmanagerange.dto.BatchDeleteRequest;
import com.epoch.app.crplatformenhance.scitemmanagerange.dto.BatchUpdateRequest;
import com.epoch.app.crplatformenhance.scitemmanagerange.dto.CreateResponse;
import com.epoch.app.crplatformenhance.scitemmanagerange.dto.DeleteResponse;
import com.epoch.app.crplatformenhance.scitemmanagerange.dto.LoadRequest;
import com.epoch.app.crplatformenhance.scitemmanagerange.dto.QueryListByIdsRequest;
import com.epoch.app.crplatformenhance.scitemmanagerange.dto.UpdateResponse;
import com.epoch.app.crplatformenhance.scitemmanagerange.model.ScItemManageRange;
import com.epoch.app.crplatformenhance.scitemmanagerange.service.ScItemManageRangeService;
import com.epoch.app.crplatformenhance.scitemmanagerangewrite.dto.BatchDisableRequest;
import com.epoch.app.crplatformenhance.scitemmanagerangewrite.dto.BatchEnableRequest;
import com.epoch.app.crplatformenhance.scitemmanagerangewrite.dto.DeleteRequest;
import com.epoch.app.crplatformenhance.scitemmanagerangewrite.dto.DisableRequest;
import com.epoch.app.crplatformenhance.scitemmanagerangewrite.dto.EnableOrDisableRequest;
import com.epoch.app.crplatformenhance.scitemmanagerangewrite.dto.EnableRequest;
import com.epoch.app.crplatformenhance.scitemmanagerangewrite.service.ScItemManageRangeWriteService;
import com.epoch.app.crplatformenhance.service.CrPlatformEnhanceService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @description: 货品经营范围写服务
 * @author: yuhw
 * @date: 2023年04月27日 20:40
 **/
@Component
@Primary
public class ScItemManageRangeWriteServiceImpl implements ScItemManageRangeWriteService {

    private static Log log = Log.getLogger(ScItemManageRangeWriteServiceImpl.class);

    @Resource
    private BaseDataService baseDataService;
    @Resource
    private CrPlatformEnhanceService crPlatformEnhanceService;
    @Resource
    private ScItemManageRangeService scItemManageRangeService;
    @Resource(name = "allocateApplyTaskExecutor")
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    @Resource
    private BcOrderService bcOrderService;

    private static final Integer MAX_PAGE_SIZE = 1000;

    /**
     * 货品经营范围新增
     * @param scItemManageRangeCreateRequest
     * @return
     */
    @Override
    @FacadeInvoker
    public Result<Long> create(ScItemManageRangeCreateRequest scItemManageRangeCreateRequest) {
        //校验参数
        validParams(scItemManageRangeCreateRequest);
        //校验销售组织
        OrganizationSDO saleOrganization = queryOrganization(scItemManageRangeCreateRequest.getSaleOrgId());
        //销售组织是否存在
        if (saleOrganization == null){
            throw new FacadeException("OTS-01-005-02-15-034");
        }
        //新增时 提交的组织id需要是销售组织层级
        if (OrganizationTypeEnum.SALES_ORGANIZATION.getCode() != saleOrganization.getType()){
            throw new FacadeException("OTS-01-005-02-15-038");
        }
        //查询提交的销售组织的上一级分子公司
        TopOrganizationListResponse bizUnitOrganization = queryBizUnitOrgBySaleOrgId(scItemManageRangeCreateRequest.getSaleOrgId());
        //不存在分子公司时报错
        if (bizUnitOrganization == null){
            throw new FacadeException("OTS-01-005-02-15-035");
        }
        //校验货品
        ScItemSDO scItemSDO = queryScItem(scItemManageRangeCreateRequest.getScItemId());
        if (scItemSDO == null || StringUtils.isBlank(scItemSDO.getScItemId())){
            throw new FacadeException("OTS-01-005-02-15-032");
        }
        //校验新增重复
        validDuplicate(scItemManageRangeCreateRequest.getSaleOrgId(),scItemManageRangeCreateRequest.getScItemId());
        //构建模型
        ScItemManageRange scItemManageRange = buildScItemManageRange(scItemSDO,saleOrganization,bizUnitOrganization,
                scItemManageRangeCreateRequest.getStatus());
        CreateResponse createResponse = scItemManageRangeService.create(scItemManageRange);
        if (createResponse == null || createResponse.getLastInsertId() == null){
            throw new FacadeException("OTS-01-005-02-15-037");
        }
        return Result.success(createResponse.getLastInsertId());
    }


    /**
     * 启用/禁用
     * @param enableOrDisableRequest
     * @return
     */
    @Override
    @FacadeInvoker
    public Result<Boolean> enableOrDisable(EnableOrDisableRequest enableOrDisableRequest) {
        ScItemManageRange scItemManageRange = getScItemManageRange(enableOrDisableRequest.getId());
        //设置当前状态的相反状态
        scItemManageRange.setStatus(ScItemManageRangeStatus.ENABLE.getValue().equals(scItemManageRange.getStatus()) ?
                ScItemManageRangeStatus.DISABLED.getValue() : ScItemManageRangeStatus.ENABLE.getValue());
        UpdateResponse updateResponse = scItemManageRangeService.update(scItemManageRange);
        if (updateResponse == null || updateResponse.getCount() != 1){
            throw new FacadeException("OTS-01-005-02-15-043");
        }
        return Result.success(true);
    }

    @Override
    @FacadeInvoker
    @Deprecated
    public Result<Boolean> enable(EnableRequest enableRequest) {
        ScItemManageRange scItemManageRange = getScItemManageRange(enableRequest.getId());
        scItemManageRange.setStatus(ScItemManageRangeStatus.ENABLE.getValue());
        scItemManageRangeService.update(scItemManageRange);
        return Result.success(true);
    }

    /**
     * 删除
     * @param deleteRequest
     * @return
     */
    @Override
    @FacadeInvoker
    public Result<Boolean> delete(DeleteRequest deleteRequest) {
        ScItemManageRange scItemManageRange = getScItemManageRange(deleteRequest.getId());
        //启用状态不能删除
        if (ScItemManageRangeStatus.ENABLE.getValue().equals(scItemManageRange.getStatus())){
            throw new FacadeException("OTS-01-005-02-15-041");
        }
        com.epoch.app.crplatformenhance.scitemmanagerange.dto.DeleteRequest delete = new com.epoch.app.crplatformenhance.scitemmanagerange.dto.DeleteRequest();
        delete.setId(deleteRequest.getId());
        DeleteResponse deleteResponse = scItemManageRangeService.delete(delete);
        if (deleteResponse == null || deleteResponse.getCount() != 1){
            throw new FacadeException("OTS-01-005-02-15-044");
        }
        return Result.success(true);
    }

    @Override
    @FacadeInvoker
    @Deprecated
    public Result<Boolean> disable(DisableRequest disableRequest) {
        ScItemManageRange scItemManageRange = getScItemManageRange(disableRequest.getId());
        scItemManageRange.setStatus(ScItemManageRangeStatus.DISABLED.getValue());
        scItemManageRangeService.update(scItemManageRange);
        return Result.success(true);
    }

    /**
     * 批量启用
     * @param batchEnableRequest
     * @return
     */
    @Override
    @FacadeInvoker
    public Result<Boolean> batchEnable(BatchEnableRequest batchEnableRequest) {
        if (CollectionUtils.isEmpty(batchEnableRequest.getIds())){
            throw new FacadeException("OTS-01-005-02-15-042");
        }
        BatchUpdateRequest batchUpdateRequest = new BatchUpdateRequest();
        batchUpdateRequest.setIds(batchEnableRequest.getIds());
        batchUpdateRequest.setStatus(ScItemManageRangeStatus.ENABLE.getValue());
        scItemManageRangeService.batchUpdate(batchUpdateRequest);
        return Result.success(true);
    }

    /**
     * 批量禁用
     * @param batchDisableRequest
     * @return
     */
    @Override
    @FacadeInvoker
    public Result<Boolean> batchDisable(BatchDisableRequest batchDisableRequest) {
        if (CollectionUtils.isEmpty(batchDisableRequest.getIds())){
            throw new FacadeException("OTS-01-005-02-15-042");
        }
        BatchUpdateRequest batchUpdateRequest = new BatchUpdateRequest();
        batchUpdateRequest.setIds(batchDisableRequest.getIds());
        batchUpdateRequest.setStatus(ScItemManageRangeStatus.DISABLED.getValue());
        scItemManageRangeService.batchUpdate(batchUpdateRequest);
        return Result.success(true);
    }

    /**
     * 批量删除
     * @param scItemManageRangeBatchDeleteRequest
     * @return
     */
    @Override
    @FacadeInvoker
    public Result<Boolean> batchDelete(ScItemManageRangeBatchDeleteRequest scItemManageRangeBatchDeleteRequest) {
        if (CollectionUtils.isEmpty(scItemManageRangeBatchDeleteRequest.getIds())){
            throw new FacadeException("OTS-01-005-02-15-042");
        }
        QueryListByIdsRequest queryListByIdsRequest = new QueryListByIdsRequest();
        queryListByIdsRequest.setIds(scItemManageRangeBatchDeleteRequest.getIds());
        queryListByIdsRequest.setLimit(MAX_PAGE_SIZE);
        Result<List<ScItemManageRange>> listResult = scItemManageRangeService.queryListByIds(queryListByIdsRequest);
        if (listResult == null || CollectionUtils.isEmpty(listResult.getResult())){
            throw new FacadeException("OTS-01-005-02-15-040");
        }
        //判断货品范围状态 启用状态下不能删除
        listResult.getResult().forEach(scItemManageRange -> {
            if (ScItemManageRangeStatus.ENABLE.getValue().equals(scItemManageRange.getStatus())){
                throw new FacadeException("OTS-01-005-02-15-041");
            }
        });
        BatchDeleteRequest batchDeleteRequest = new BatchDeleteRequest();
        batchDeleteRequest.setIds(scItemManageRangeBatchDeleteRequest.getIds());
        scItemManageRangeService.batchDelete(batchDeleteRequest);
        return Result.success(true);
    }

    /**
     * excel导入货品经营范围
     * @param scItemManageRangeImportListRequest
     * @return
     */
    @Override
    @FacadeInvoker
    public Result<List<ScItemManageRangeImportRequest>> importData(ScItemManageRangeImportListRequest scItemManageRangeImportListRequest) {
        long start = System.currentTimeMillis();
        //获取当前登录人信息
        EmployeeGetCurrentLoginResponse loginResponse = bcOrderService.employeeGetCurrentLogin();
        String relatedOrganizationId = loginResponse.getRelatedOrganizationId();
        String employeeId = loginResponse.getEmployeeId();

        Integer type = Integer.parseInt(loginResponse.getRelatedOrganizationType());
        //是否需要检查销售组织,分子公司层级及向下的需要校验销售组织
        boolean needCheckSaleOrg = true;
        //分子公司层级及向下的销售组织列表
        List<String> saleOrgIds = Lists.newArrayList();
        if (type < OrganizationTypeEnum.COMPANY.getCode()){
            //不限制查询权限
            needCheckSaleOrg = false;
        }else if (type == OrganizationTypeEnum.COMPANY.getCode()){
            //分子公司层级可以导入该改分子公司下的
            saleOrgIds = getDownSaleOrgList(relatedOrganizationId);
        }else if (type == OrganizationTypeEnum.SALES_ORGANIZATION.getCode()){
            //销售组织的只能导入该销售的
            saleOrgIds.add(relatedOrganizationId);
        }else {
            //获取渠道/部门的销售组织这一层级
            saleOrgIds = getTopSaleOrgList(relatedOrganizationId);
        }

        List<ScItemManageRangeImportRequest> importRequestList = scItemManageRangeImportListRequest.getImportRequestList();
        //导入校验
        importCheck(importRequestList);
        //筛选出初步校验通过的数据行
        List<ScItemManageRangeImportRequest> checkSuccessList = importRequestList.stream().filter(x -> StringUtils.isBlank(x.getErrorMessage())).collect(Collectors.toList());
        //销售组织编码
        List<String> saleOrgCodes = checkSuccessList.stream().map(ScItemManageRangeImportRequest::getSaleOrgCode).distinct().collect(Collectors.toList());

        //货品编码
        List<String> scItemCodes  = checkSuccessList.stream().map(ScItemManageRangeImportRequest::getScItemCode).distinct().collect(Collectors.toList());
        //获取导入的销售组织
        List<OrganizationSDO> saleOrgList = getSaleOrgList(saleOrgCodes);

        List<ScItemSDO> scItems = getScItems(scItemCodes);
        Map<String, OrganizationSDO> saleOrgMap = saleOrgList.stream().collect(Collectors.toMap(OrganizationSDO::getCode, Function.identity(), (a, b) -> a));
        Map<String, ScItemSDO> scItemSDOMap = scItems.stream().collect(Collectors.toMap(ScItemSDO::getOuterId, Function.identity(), (a, b) -> a));
        //分子公司层级
        Map<String, OrganizationSDO> bizUnitMap = getBizUnitMap(saleOrgList);

        boolean finalNeedCheckSaleOrg = needCheckSaleOrg;
        List<String> finalSaleOrgIds = saleOrgIds;
        List<Future> futureList = Lists.newArrayList();
        checkSuccessList.forEach(request -> {
            try{
                CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                    importScItemManageRange(finalNeedCheckSaleOrg, finalSaleOrgIds, saleOrgMap, scItemSDOMap, bizUnitMap, request,employeeId);
                }, threadPoolTaskExecutor);
                futureList.add(future);
            }catch (Throwable e){
                log.error("importScItemManageRange_error",e);
            }
        });
        for (Future future : futureList) {
            try {
                future.get();
            } catch (Throwable e) {
                e.printStackTrace();
                log.error("importScItemManageRange_error",e);
            }
        }
        //获取组织和货品
        log.info("import_scItem_manage_cost:{}",System.currentTimeMillis() - start);
        return Result.success(importRequestList);
    }

    private void importScItemManageRange(boolean needCheckSaleOrg, List<String> saleOrgIds, Map<String, OrganizationSDO> saleOrgMap, Map<String, ScItemSDO> scItemSDOMap, Map<String, OrganizationSDO> bizUnitMap, ScItemManageRangeImportRequest request,
                                         String employeeId) {
        if (!saleOrgMap.containsKey(request.getSaleOrgCode())){
            request.setErrorMessage("销售组织不存在");
            return;
        }
        if (!scItemSDOMap.containsKey(request.getScItemCode())){
            request.setErrorMessage("货品编码不存在");
            return;
        }
        OrganizationSDO organizationSDO = saleOrgMap.get(request.getSaleOrgCode());
        if (!OrganizationTypeEnum.SALES_ORGANIZATION.getCode().equals(organizationSDO.getType())){
            request.setErrorMessage("非销售组织的编码");
            return;
        }
        if (needCheckSaleOrg && !saleOrgIds.contains(organizationSDO.getId())){
            request.setErrorMessage("没有权限导入");
            return;
        }
        ScItemSDO scItemSDO = scItemSDOMap.get(request.getScItemCode());
        OrganizationSDO bizUnitOrganizationSDO = bizUnitMap.get(organizationSDO.getParentId());

        if (StringUtils.isNotBlank(request.getSaleOrgName()) && !request.getSaleOrgName().equals(organizationSDO.getName())){
            request.setErrorMessage("销售组织名称不匹配");
            return;
        }
        if (StringUtils.isNotBlank(request.getScItemName()) && !request.getScItemName().equals(scItemSDO.getTitle())){
            request.setErrorMessage("货品名称不匹配");
            return;
        }
        try{
            //校验分子公司经营货品范围是否重复
            ScItemManageRangeLoadListRequest loadListRequest = new ScItemManageRangeLoadListRequest();
            loadListRequest.setScItemCode(request.getScItemCode());
            loadListRequest.setSaleOrgCode(request.getSaleOrgCode());
            Result<List<ScItemManageRange>> listResult = scItemManageRangeService.loadList(loadListRequest);
            if (listResult != null && CollectionUtils.isNotEmpty(listResult.getResult())){
                request.setErrorMessage("分子公司经营货品已存在");
                return;
            }
            ScItemManageRange scItemManageRange = getScItemManageRange(organizationSDO, scItemSDO, bizUnitOrganizationSDO,employeeId);
            scItemManageRangeService.create(scItemManageRange);
        }catch (Throwable e){
            log.error("ScItemManageRangeWriteServiceImpl_import_error",e);
            if (StringUtils.isNotBlank(e.getMessage()) && e.getMessage().contains("Duplicate entry")){
                request.setErrorMessage("分子公司经营货品已存在");
            }else {
                request.setErrorMessage("导入异常");
            }
            return;
        }
    }

    //组装货品范围数据
    private ScItemManageRange getScItemManageRange(OrganizationSDO organizationSDO, ScItemSDO scItemSDO, OrganizationSDO bizUnitOrganizationSDO,String employeeId) {
        ScItemManageRange scItemManageRange = new ScItemManageRange();
        scItemManageRange.setScItemId(scItemSDO.getScItemId());
        scItemManageRange.setScItemCode(scItemSDO.getOuterId());
        scItemManageRange.setScItemName(scItemSDO.getTitle());
        scItemManageRange.setStatus(ScItemManageRangeStatus.DISABLED.getValue());
        scItemManageRange.setSaleOrgId(organizationSDO.getId());
        scItemManageRange.setSaleOrgCode(organizationSDO.getCode());
        scItemManageRange.setSaleOrgName(organizationSDO.getName());
        if (bizUnitOrganizationSDO != null){
            scItemManageRange.setBizUnitId(bizUnitOrganizationSDO.getId());
            scItemManageRange.setBizUnitCode(bizUnitOrganizationSDO.getCode());
            scItemManageRange.setBizUnitName(bizUnitOrganizationSDO.getName());
        }
        scItemManageRange.setCreator(employeeId);
        scItemManageRange.setUpdater(employeeId);
        return scItemManageRange;
    }

    //根据销售组织层级获取分子公司数据
    private Map<String,OrganizationSDO> getBizUnitMap(List<OrganizationSDO> organizationSDOS){
        List<String> parentIds = organizationSDOS.stream().map(OrganizationSDO::getParentId).distinct().collect(Collectors.toList());
        Map<String,OrganizationSDO> map = Maps.newHashMap();
        if (CollectionUtils.isNotEmpty(parentIds)){
            BaselineGetOrganizationByIds2Request byIds2Request = new BaselineGetOrganizationByIds2Request();
            byIds2Request.setIds(parentIds);
            BaselineGetOrganizationByIds2Response response = baseDataService.baselineGetOrganizationByIds2(byIds2Request);
            if (response != null && CollectionUtils.isNotEmpty(response.getResult())){
                map = response.getResult().stream().collect(Collectors.toMap(OrganizationSDO::getId, Function.identity(), (a, b) -> a));
            }
        }
        return map;
    }

    /**
     * excel导入数据基本校验
     * @param requests
     */
    private void importCheck(List<ScItemManageRangeImportRequest> requests){
        if (CollectionUtils.isEmpty(requests)){
            return;
        }
        for (ScItemManageRangeImportRequest request : requests) {
            if (StringUtils.isBlank(request.getSaleOrgCode())){
                request.setErrorMessage("销售组织编码不能为空");
                continue;
            }
            if (StringUtils.isBlank(request.getScItemCode())){
                request.setErrorMessage("货品编码不能为空");
            }
            trim(request);
        }
        requests.stream().collect(Collectors.groupingBy(request -> Optional.ofNullable(request.getSaleOrgCode() + request.getScItemCode()))).values().forEach(r->{
            if (CollectionUtils.isNotEmpty(r) && r.size() > 1){
                r.forEach(request -> {
                    if (StringUtils.isBlank(request.getErrorMessage())){
                        request.setErrorMessage("导入数据中含有重复的销售组织+货品编码");
                    }
                });
            }
        });
    }

    //去空格
    private void trim(ScItemManageRangeImportRequest request){
        if (request == null){
            return;
        }
        if (StringUtils.isNotBlank(request.getScItemCode())){
            request.setScItemCode(request.getScItemCode().trim());
        }
        if (StringUtils.isNotBlank(request.getSaleOrgCode())){
            request.setSaleOrgCode(request.getSaleOrgCode().trim());
        }
    }

    //获取销售组织列表
    private List<OrganizationSDO>  getSaleOrgList(List<String> saleOrgCodes){
        if (CollectionUtils.isEmpty(saleOrgCodes)){
            return Lists.newArrayList();
        }
        BaselineGetOrganizationByCodes2Request baselineGetOrganizationByCodes2Request = new BaselineGetOrganizationByCodes2Request();
        baselineGetOrganizationByCodes2Request.setIds(saleOrgCodes);
        BaselineGetOrganizationByCodes2Response response = baseDataService.baselineGetOrganizationByCodes2(baselineGetOrganizationByCodes2Request);
        if (response != null && CollectionUtils.isNotEmpty(response.getResult())){
            return response.getResult();
        }
        return Lists.newArrayList();
    }

    //货品编码查询有效货品
    private List<ScItemSDO> getScItems(List<String> scItemCodes){
        if (CollectionUtils.isEmpty(scItemCodes)){
            return Lists.newArrayList();
        }
        BaselineQueryScItemByPageFromDbRequest dbRequest = new BaselineQueryScItemByPageFromDbRequest();
        dbRequest.setOutIdList(scItemCodes);
        dbRequest.setBusinessType("11");//业态常温
        dbRequest.setType(0);//非组合货品
        dbRequest.setStatusList(Lists.newArrayList(1));//只查有效
        dbRequest.setLimit(MAX_PAGE_SIZE);
        Object result = baseDataService.baselineQueryScItemByPageFromDb(dbRequest);
        ScItemDBresponse scItemDBresponse = JSON.parseObject(JSON.toJSONString(result), ScItemDBresponse.class);
        //总条数
        Integer total = getScItemSearchResult(scItemDBresponse)
                .map(ScItemSearchResult::getTotal)
                .orElse(0);
        //货品返回结果集
        List<ScItemSDO> scItemSDOList = Lists.newArrayList();
        //查询转换后的货品数据
        List<ScItemSDO> scItemSDOS = getScItemSearchResult(scItemDBresponse)
                .map(ScItemSearchResult::getSearchResult)
                .orElse(Lists.newArrayList());
        if (CollectionUtils.isNotEmpty(scItemSDOS)){
            scItemSDOList.addAll(scItemSDOS);
        }
        //如果总数大于分页条数
        if (total > MAX_PAGE_SIZE){
            int page = PageUtils.getTotalPage(total,MAX_PAGE_SIZE);
            for (int i = 2; i <= page; i++) {
                //从第二页开始查询
                dbRequest.setPage(i);
                result = baseDataService.baselineQueryScItemByPageFromDb(dbRequest);
                scItemDBresponse = JSON.parseObject(JSON.toJSONString(result),ScItemDBresponse.class);

                scItemSDOS = getScItemSearchResult(scItemDBresponse)
                        .map(ScItemSearchResult::getSearchResult)
                        .orElse(Lists.newArrayList());
                if (CollectionUtils.isNotEmpty(scItemSDOS)){
                    scItemSDOList.addAll(scItemSDOS);
                }
            }
        }
        return scItemSDOList;
    }
    //获取货品结果
    private Optional<ScItemSearchResult> getScItemSearchResult(ScItemDBresponse scItemDBresponse) {
        return Optional.ofNullable(scItemDBresponse)
                .map(ScItemDBresponse::getResult)
                .map(ScItemResult::getResult);
    }

    //查询分子公司下所有的销售组织id列表
    private List<String> getDownSaleOrgList(String bizUnitId){
        if (StringUtils.isBlank(bizUnitId)){
            return Lists.newArrayList();
        }
        GetDownOrganizationListRequest request = new GetDownOrganizationListRequest();
        request.setId(bizUnitId);
        request.setType(OrganizationTypeEnum.SALES_ORGANIZATION.getCode());
        Result<List<com.epoch.app.crplatformenhance.sdo.OrganizationSDO>> downOrganizationList = crPlatformEnhanceService.getDownOrganizationList(request);
        if (downOrganizationList != null && CollectionUtils.isNotEmpty(downOrganizationList.getResult())){
            return downOrganizationList.getResult().stream()
                    .filter(x-> OrganizationTypeEnum.SALES_ORGANIZATION.getCode().equals(x.getType()))
                    .map(com.epoch.app.crplatformenhance.sdo.OrganizationSDO::getId)
                    .distinct().collect(Collectors.toList());
        }
        return Lists.newArrayList();
    }
    //查询渠道/部门的上级销售组织
    private List<String> getTopSaleOrgList(String id){
        if (StringUtils.isBlank(id)){
            return Lists.newArrayList();
        }
        GetTopOrganizationListRequest getTopOrganizationListRequest = new GetTopOrganizationListRequest();
        getTopOrganizationListRequest.setId(id);
        getTopOrganizationListRequest.setType(OrganizationTypeEnum.SALES_ORGANIZATION.getCode());
        Result<List<TopOrganizationListResponse>> topOrganizationList = crPlatformEnhanceService.getTopOrganizationList(getTopOrganizationListRequest);
        if (topOrganizationList != null && CollectionUtils.isNotEmpty(topOrganizationList.getResult())){
            return topOrganizationList.getResult().stream().filter(topOrganizationListResponse -> OrganizationTypeEnum.SALES_ORGANIZATION.getCode().equals(topOrganizationListResponse.getType()))
                    .map(TopOrganizationListResponse::getId).collect(Collectors.toList());
        }
        return Lists.newArrayList();
    }

    //新增请求 校验参数
    private void validParams(ScItemManageRangeCreateRequest createRequest){
        if (StringUtils.isBlank(createRequest.getSaleOrgId())){
            throw new FacadeException("OTS-01-005-02-15-030");
        }
        if (StringUtils.isBlank(createRequest.getScItemId())){
            throw new FacadeException("OTS-01-005-02-15-031");
        }
        if (createRequest.getStatus() == null){
            throw new FacadeException("OTS-01-005-02-15-045");
        }
        ScItemManageRangeStatus status = Arrays.stream(ScItemManageRangeStatus.values())
                .filter(target-> Objects.equals(target.getValue(),createRequest.getStatus()))
                .findFirst().orElse(null);
        if (status == null){
            throw new FacadeException("OTS-01-005-02-15-046");
        }
    }
    //根据货品id查货品
    private ScItemSDO queryScItem(String scItemId){
        BaselineQueryScItemByPageFromDbRequest dbRequest = new BaselineQueryScItemByPageFromDbRequest();
        dbRequest.setIdList(Lists.newArrayList(scItemId));
        //只查有效
        dbRequest.setStatusList(Lists.newArrayList(1));
        Object result = baseDataService.baselineQueryScItemByPageFromDb(dbRequest);
        ScItemDBresponse scItemDBresponse = JSON.parseObject(JSON.toJSONString(result), ScItemDBresponse.class);
        return getScItemSearchResult(scItemDBresponse)
                .map(ScItemSearchResult::getSearchResult)
                .map(scItemSDOS -> scItemSDOS.size()> 0 ? scItemSDOS.get(0) : null)
                .orElse(null);
    }
    //根据组织id查组织
    private OrganizationSDO queryOrganization(String organizationId){
        if (StringUtils.isBlank(organizationId)){
            return null;
        }
        BaselineGetOrganizationByIds2Request baselineGetOrganizationByIds2Request = new BaselineGetOrganizationByIds2Request();
        baselineGetOrganizationByIds2Request.setIds(Lists.newArrayList(organizationId));
        BaselineGetOrganizationByIds2Response baselineGetOrganizationByIds2Response = baseDataService.baselineGetOrganizationByIds2(baselineGetOrganizationByIds2Request);
        return Optional.ofNullable(baselineGetOrganizationByIds2Response).map(BaselineGetOrganizationByIds2Response::getResult)
                .map(organizationSDOS -> organizationSDOS.isEmpty() ? null : organizationSDOS.get(0)).orElse(null);
    }

    //查询当前销售组织的分子公司组织
    private TopOrganizationListResponse queryBizUnitOrgBySaleOrgId(String organizationId){
        if (StringUtils.isBlank(organizationId)){
            return null;
        }
        GetTopOrganizationListRequest getTopOrganizationListRequest = new GetTopOrganizationListRequest();
        getTopOrganizationListRequest.setId(organizationId);
        getTopOrganizationListRequest.setType(OrganizationTypeEnum.COMPANY.getCode());
        Result<List<TopOrganizationListResponse>> topOrganizationList = crPlatformEnhanceService.getTopOrganizationList(getTopOrganizationListRequest);
        if (topOrganizationList != null && CollectionUtils.isNotEmpty(topOrganizationList.getResult())){
            return topOrganizationList.getResult().stream().filter(topOrganizationListResponse -> OrganizationTypeEnum.COMPANY.getCode().equals(topOrganizationListResponse.getType()))
                    .findFirst().orElse(null);
        }
        return null;
    }

    //构建货品经营范围
    private ScItemManageRange buildScItemManageRange(ScItemSDO scItemSDO, OrganizationSDO saleOrg, TopOrganizationListResponse bizUnit, Integer status){
        ScItemManageRange scItemManageRange = new ScItemManageRange();
        //销售组织
        scItemManageRange.setSaleOrgId(saleOrg.getId());
        scItemManageRange.setSaleOrgCode(saleOrg.getCode());
        scItemManageRange.setSaleOrgName(saleOrg.getName());

        //分子公司
        scItemManageRange.setBizUnitId(bizUnit.getId());
        scItemManageRange.setBizUnitCode(bizUnit.getCode());
        scItemManageRange.setBizUnitName(bizUnit.getName());
        //货品信息
        scItemManageRange.setScItemId(scItemSDO.getScItemId());
        scItemManageRange.setScItemCode(scItemSDO.getOuterId());
        scItemManageRange.setScItemName(scItemSDO.getTitle());
        scItemManageRange.setStatus(status);
        return scItemManageRange;

    }

    //校验货品范围重复
    private void validDuplicate(String saleOrgId,String scItemId){
        ScItemManageRangeLoadListRequest scItemManageRangeLoadListRequest = new ScItemManageRangeLoadListRequest();
        scItemManageRangeLoadListRequest.setSaleOrgId(saleOrgId);
        scItemManageRangeLoadListRequest.setScItemId(scItemId);
        Result<List<ScItemManageRange>> listResult = scItemManageRangeService.loadList(scItemManageRangeLoadListRequest);
        if (listResult !=null && CollectionUtils.isNotEmpty(listResult.getResult())){
            throw new FacadeException("OTS-01-005-02-15-036");
        }
    }

    /**
     * 校验id 并根据id查询出货品经营范围
     * @param id
     * @return
     */
    private ScItemManageRange getScItemManageRange(Long id){
        if (id == null){
            throw new FacadeException("OTS-01-005-02-15-039");
        }
        LoadRequest loadRequest = new LoadRequest(id);
        ScItemManageRange scItemManageRange = scItemManageRangeService.load(loadRequest);
        if (scItemManageRange == null){
            throw new FacadeException("OTS-01-005-02-15-040");
        }
        return scItemManageRange;
    }
    
}
